//
//  RotationView.m
//  Animation
//
//  Created by wenbin Ding on 14-11-27.
//  Copyright (c) 2014年 PINGAN. All rights reserved.
//

#import "RotationView.h"
#import <QuartzCore/QuartzCore.h>

#define DEGREES_TO_RADIANS(d) (d * M_PI / 180.0)

NSString *const RVRotationAnimationKey = @"RotationAnimation";

@interface RotationView ()
{
    /// 动画正在执行为YES 停止为NO
    BOOL bAnimationStatus;
}
@end

@implementation RotationView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        [self configView];
    }
    return self;
}

- (void)awakeFromNib
{
    [self configView];
}

- (void)configView
{
    bAnimationStatus = NO;
}

#pragma mark - 动画相关 逻辑
- (void)startLayer
{
    if (![self.layer animationForKey:RVRotationAnimationKey])
    {
        CABasicAnimation *rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
        
        rotationAnimation.toValue = [NSNumber numberWithFloat:DEGREES_TO_RADIANS(-360)];
        rotationAnimation.repeatCount = INT_MAX;
        // note : 更改速度的时候注意timeOffset的修改
        rotationAnimation.speed =0.4;
        rotationAnimation.autoreverses = NO;
        rotationAnimation.removedOnCompletion = NO;
        
        [self.layer addAnimation:rotationAnimation forKey:RVRotationAnimationKey];
        
        bAnimationStatus = YES;
    }
    else
    {
        [self resumeLayer];
    }
}

- (void)pauseLayer
{
    if (bAnimationStatus) {
        CFTimeInterval pausedTime = [self.layer convertTime:CACurrentMediaTime() fromLayer:nil];
        self.layer.speed = 0.0;
        self.layer.timeOffset = pausedTime;
        bAnimationStatus = NO;
    }
}

- (void)resumeLayer
{
    if (!bAnimationStatus) {
        CFTimeInterval pausedTime = [self.layer timeOffset];
        self.layer.speed = 1.0;
        self.layer.timeOffset = 0.0;
        self.layer.beginTime = 0.0;
        CFTimeInterval timeSincePause = [self.layer convertTime:CACurrentMediaTime() fromLayer:nil] - pausedTime;
        self.layer.beginTime = timeSincePause;
        bAnimationStatus = YES;
    }
}

- (void)removeRotationAnimation
{
    [self.layer removeAnimationForKey:RVRotationAnimationKey];
    bAnimationStatus = NO;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

@end
